package com.miyin.twwwwww;

import com.miyin.twpull.service.TwCommonService;
import com.miyin.twpull.service.impl.TwCommonServiceImpl;
import com.twitter.clientlib.ApiException;
import com.twitter.clientlib.TwitterCredentialsBearer;
import com.twitter.clientlib.TwitterCredentialsOAuth2;
import com.twitter.clientlib.api.TwitterApi;
import com.twitter.clientlib.model.MultiUserLookupResponse;
import com.twitter.clientlib.model.ResourceUnauthorizedProblem;
import com.twitter.clientlib.model.SingleTweetLookupResponse;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TestSdkUse {

    /**
     * oAuth2.0
     */
    public void test(){
        /**
         * Set the credentials for the required APIs.
         * The Java SDK supports TwitterCredentialsOAuth2 & TwitterCredentialsBearer.
         * Check the 'security' tag of the required APIs in https://api.twitter.com/2/openapi.json in order
         * to use the right credential object.
         */
        TwitterApi apiInstance = new TwitterApi();
        TwitterCredentialsOAuth2 credentials = new TwitterCredentialsOAuth2(System.getenv("TWITTER_OAUTH2_CLIENT_ID"),
                System.getenv("TWITTER_OAUTH2_CLIENT_SECRET"),
                System.getenv("TWITTER_OAUTH2_ACCESS_TOKEN"),
                System.getenv("TWITTER_OAUTH2_REFRESH_TOKEN"));
        apiInstance.setTwitterCredentials(credentials);

        Set<String> tweetFields = new HashSet<>();
        tweetFields.add("author_id");
        tweetFields.add("id");
        tweetFields.add("created_at");

        try {
            // findTweetById
            SingleTweetLookupResponse result = apiInstance.tweets().findTweetById("20", null, tweetFields, null , null, null, null);
            if(result.getErrors() != null && result.getErrors().size() > 0) {
                System.out.println("Error:");

                result.getErrors().forEach(e -> {
                    System.out.println(e.toString());
                    if (e instanceof ResourceUnauthorizedProblem) {
                        System.out.println(((ResourceUnauthorizedProblem) e).getTitle() + " " + ((ResourceUnauthorizedProblem) e).getDetail());
                    }
                });
            } else {
                System.out.println("findTweetById - Tweet Text: " + result.toString());
            }
        } catch (ApiException e) {
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }

    /**
     * 不记名令牌方式Bearer_token
     */
    public void testBearerTokenPull(){
        /**
         * Set the credentials for the required APIs.
         * The Java SDK supports TwitterCredentialsOAuth2 & TwitterCredentialsBearer.
         * Check the 'security' tag of the required APIs in https://api.twitter.com/2/openapi.json in order
         * to use the right credential object.
         */
//        TwitterCredentialsBearer credentials = new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN"));
//        TwitterApi apiInstance = new TwitterApi();
//        apiInstance.setTwitterCredentials(credentials);

        TwitterApi apiInstance = new TwCommonServiceImpl().getTwitterApiByBearerToken();

        Set<String> tweetFields = new HashSet<>();
        tweetFields.add("author_id");
        tweetFields.add("id");
        tweetFields.add("created_at");

        try {
            InputStream streamResult = apiInstance.tweets().sampleStream(null, tweetFields, null , null, null, null, 0);
            // sampleStream with TweetsStreamListenersExecutor
            Responder responder = new Responder();
            TweetsStreamListenersExecutor tsle = new TweetsStreamListenersExecutor(streamResult);
            tsle.addListener(responder);
            tsle.executeListeners();

//       Shutdown TweetsStreamListenersExecutor
//      try {
//        Thread.sleep(20000);
//        tsle.shutdown();
//      } catch (InterruptedException e) {
//        e.printStackTrace();
//      }

//      // An example of how to use the streaming directly using the InputStream result (Without TweetsStreamListenersExecutor)
//      try{
//         JSON json = new JSON();
//         Type localVarReturnType = new TypeToken<StreamingTweet>(){}.getType();
//         BufferedReader reader = new BufferedReader(new InputStreamReader(streamResult));
//         String line = reader.readLine();
//         while (line != null) {
//           if(line.isEmpty()) {
//             System.err.println("==> " + line.isEmpty());
//             line = reader.readLine();
//             continue;
//            }
//           Object jsonObject = json.getGson().fromJson(line, localVarReturnType);
//           System.out.println(jsonObject != null ? jsonObject.toString() : "Null object");
//           line = reader.readLine();
//         }
//      }catch (Exception e) {
//        e.printStackTrace();
//        System.out.println(e);
//      }
        } catch (ApiException e) {
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        Set<String> expansions = new HashSet<>(Arrays.asList());
//        Set<String> tweetFields = new HashSet<>(Arrays.asList());
//        Set<String> userFields = new HashSet<>(Arrays.asList(
//                "created_at",
//                "description",
//                "entities,id",
//                "location,name",
//                "pinned_tweet_id",
//                "profile_image_url",
//                "protected",
//                "public_metrics",
//                "url",
//                "username",
//                "verified",
//                "withheld"));
//
//        List<String> usernames = Arrays.asList("TheMoonCarl");
//
//        try {
//            MultiUserLookupResponse result = new TwCommonServiceImpl().getTwitterApiByBearerToken().users().findUsersByUsername(usernames, expansions, tweetFields, userFields);
//            System.out.println(result);
//        } catch (ApiException e) {
//            System.err.println("Exception when calling UsersApi#findUserByUsername");
//            System.err.println("Status code: " + e.getCode());
//            System.err.println("Reason: " + e.getResponseBody());
//            System.err.println("Response headers: " + e.getResponseHeaders());
//            e.printStackTrace();
//        }
//    }

}




